package top.cardone.data.support;

import com.google.common.collect.Lists;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.core.util.func.Func0;
import top.cardone.core.util.func.Func1;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/8/9.
 */
public class DefaultPageSupport implements PageSupport {
    @Override
    public <T> Page<T> newPage(List<T> content, Map<String, ?> paramMap, long total) {
        Pageable pageable = ApplicationContextHolder.func(PageableSupport.class, pageableSupport -> pageableSupport.newPageable(paramMap));

        return newPage(content, pageable, total);
    }

    @Override
    public <T> Page<T> newPage(List<T> content, Pageable pageable, long total) {
        return new PageImpl<>(content, pageable, total);
    }

    @Override
    public <T> Page<T> newPage(Func1<List<T>, Pageable> contentFunc, Map<String, ?> paramMap, Func0<Long> totalFunc) {
        long total = totalFunc.func();

        if (total < 1) {
            return new PageImpl<>(Lists.newArrayList());
        }

        Pageable pageable = ApplicationContextHolder.func(PageableSupport.class, pageableSupport -> pageableSupport.newPageable(paramMap));

        if (total < pageable.getOffset()) {
            return new PageImpl<>(Lists.newArrayList());
        }

        List<T> content = contentFunc.func(pageable);

        return new PageImpl<>(content, pageable, total);
    }

    @Override
    public <T> Page<T> newPage(Func0<List<T>> contentFunc, Pageable pageable, Func0<Long> totalFunc) {
        long total = totalFunc.func();

        if ((total < 1) || (total < pageable.getOffset())) {
            return new PageImpl<>(Lists.newArrayList());
        }

        List<T> content = contentFunc.func();

        return new PageImpl<>(content, pageable, total);
    }
}
